<?php

defined('BASEPATH') or die('forbidden');

/**
 * 后台判断权限
 * @param int $rank
 * @param string $catalog
 * @param string $action
 * @param string $segment
 */
function check_level($rank = 50, $catalog = null, $action = null, $segment = null) {
	$framework = &get_instance('controller');
	$action = $action == 'flexigrid' ? 'index' : $action;
	$segment = $segment == 'flexigrid' ? 'index' : $segment;
	$type = $framework->input->post("type");
	//AJAX操作时提示的权限
	$action = $action == 'multi' && $type == 'delete' ? 'delete' : ($action == 'multi' ? 'edit' : $action);
	$segment = $segment == 'multi' && $type == 'delete' ? 'delete' : ($segment == 'multi' ? 'edit' : $segment);
	if (!$framework->auth->is_login()) {
		if (is_ajax()) {
			json_output(0, $framework->auth->error);
		} else {
			error($framework->auth->error, str_replace('/api/', '', $framework->config['host_url_backstage']) . site_url('index/login/') . '?url=' . current_url(1), 1000);
		}
	}
	if (!$framework->auth->check_level($rank, $catalog, $action, $segment)) {
		if (segment(0) == 'index' || segment(0) == '') {
			$framework->auth->logout(base_url());
			go(site_url('index/login'));
		} else {
			if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
				json_output(0, translate('C_INSUFFICIENT_PERMISSIONS'));
			} else {
				show_error(translate('C_INSUFFICIENT_PERMISSIONS'), 403, translate('ERROR') . translate('C_INSUFFICIENT_PERMISSIONS') . "...");
			}
		}
	}
}

/**
 * 判断会员是否登录
 * @return boolean
 */
function check_login() {
	$framework = &get_instance('controller');
	return !$framework->auth->is_login() ? false : true;
}

/**
 * 后台菜单权限判断
 * @param int $rank 权限等级
 * @param string $catalog 目录
 * @param string $action 动作
 * @return mixed
 */
function check_level_menu($rank = 1, $catalog = null, $action = null, $segment = null) {
	$framework = &get_instance('controller');
	return $framework->auth->check_level($rank, $catalog, $action, $segment);
}

function get_user_search($name) {
	return "<a href=\"javascript:;\" class=\"searchit\" name=\"{$name}\" title=\"" . translate('DETAIL') . "\"><img src=\"images/search.png\" /></a>";
}

function get_role_data($role_id) {
	$framework = &get_instance('controller');
	$list = $framework->db->simple("SELECT * FROM {pre}role");
	$one = array();
	foreach ($list as $m => $n) {
		if ($n['id'] == $role_id) {
			$one = $n;
			break;
		}
	}
	if ($one) {
		if ($one['rank'] == 100) {
			$result = array();
			foreach ($list as $m => $n) {
				$result[$n['id']] = $n;
			}
			return $result;
		} else {
			return get_role_childen_data($list, $one['id']);
		}
	} else {
		return array();
	}
}

function get_role_childen_data($list, $father_id = 0) {
	$result = array();
	foreach ($list as $m => $n) {
		if ((string) $n['father_id'] === (string) $father_id) {
			$result[$n['id']] = $n;
			$result = $result + get_role_childen_data($list, $n['id']);
		}
	}
	return $result;
}

function get_role_childen_ids($role_id) {
	$list = get_role_data($role_id);
	$ids = array();
	foreach ($list as $m => $n) {
		$ids[] = $n['id'];
	}
	return $ids;
}

/**
 * 提示信息
 * @param string $result  结果 success,error
 * @param int $id 刷新的行ID,将会将该行高亮闪烁
 * @param string $refresh_id 刷新的列表ID
 */
function cp_tips($result, $id = 0, $refresh_id = "#flexigrid") {
	$dialogclose = $result == 'success' ? "window.parent.$.dialog.close('edit');
    window.parent.$.dialog.close('add');
    window.parent.$.dialog.close('dialogit');" : "";
	$text = $result == 'success' ? translate('C_TIPS_SUCCESS_TEXT') : translate('C_TIPS_ERROR_TEXT');
	//指定元素背景渐变
	$callback = $id ? ",window.parent.row_flash('{$id}')" : '';
	echo "<script type='text/javascript'>
    window.parent.SG.admin.{$result}('{$text}',0,'{$refresh_id}' {$callback});
    {$dialogclose}
    </script>";
    exit;
}

/**
 * 设置分区复选框
 * @param string    $var        html控件的名字
 * @param mixed     $selected   0 选择所有 , array(1,3)表示选择1,3区
 * @param array     $params     不明
 */
function set_area_list_view($var, $selected = '0', $params = array()) {
	$framework = &get_instance('controller');
	$arealist = get_area_list_detal();
	foreach ($arealist as $k => $v) {
		$arealist[$k] = $k . "- " . $v["name"];
	}
	$params = array_merge(array('multiple' => 'multiple', 'class' => 'multiselect'), $params);
	$params['id'] = isset($params['id']) ? $params['id'] : 'areaIds';
	if ($selected == '0') {
		$selected = array_keys($arealist);
	}
	$framework->view->assign($var, str_replace(array("\r\n", "\n", "\n"), '', $framework->form->select("areaIds", $arealist, $selected, $params, false)));
	return true;
}

/*
 * 得到区号与区名的对应关系
 */
function get_area_list_option() {
	$framework = &get_instance('controller');
	$framework->db->query("SELECT * FROM {pre}areasample ORDER BY weigh DESC", "list");
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$areainfo[$row['id']] = $row['id']."-".$row['name'];
	}
	return $areainfo;
}

/**
 * 得到url与区名的对应关系
 * 
 */
function get_area_list_host() {

	$framework = &get_instance('controller');
	$framework->db->query("SELECT * FROM {pre}areasample ORDER BY weigh DESC", "list");	
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$areainfo[$row['host']] = $row['id']."-".$row['name'];
	}
	return $areainfo;
}

/**
 * 得到区号的详细信息url
 * 
 */
function get_area_list_url() {
	//var_dump($this->db);
	$framework = &get_instance('controller');
	//var_dump($framework->db);
	$framework->db->query("SELECT * FROM {pre}areasample ORDER BY weigh DESC", "list");
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$areainfo[$row['id']] = $row['host'];
	}
	return $areainfo;
}


/**
 * 得到区号的详细信息
 * 
 */
function get_area_list_detal() {
	$framework = &get_instance('controller');
	$framework->db->query("SELECT * FROM {pre}areasample ORDER BY weigh DESC", "list");
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$areainfo[$row['id']] = $row;
	}
	return $areainfo;
}

/**
 * 获得当前有心跳的服务器
 * @return array
 */
function get_area_list_live() {
	$framework = &get_instance('controller');
	$framework->db->query("SELECT * FROM {pre}area_current", "list");
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		//如果
		if (strtotime($row['updatetime']) > (time() - 30)) {
			$areainfo[$row['id']] = $row;
		}
	}
	return $areainfo;
}

/**
 * 获得type_object ID和Name对应的数组（商城与type_object中的数据）
 * @return array
 */
function get_type_object_id_name() {
	//把type表读到内存中来
	$typelist=array();
	$config = get_config();
    $controller = &get_instance("controller");
	$controller->load->database('type_db');
	$sql = "SELECT id, name FROM type_object ";
	$controller->type_db->query($sql);
	while ($rowtype = $controller->type_db->get_array()) {
		//几个特殊的标识需要转换下
		$typelist[$rowtype['id']] = trim($rowtype['name']);
	}
	$controller->type_db->free_all();

	$controller->load->database('center_db');
	$sql = "SELECT id, name FROM dynamic_type_object ";
	$controller->center_db->query($sql);
	while ($rowtype = $controller->center_db->get_array()) {
		//几个特殊的标识需要转换下
		$typelist[$rowtype['id']] = trim($rowtype['name']);
	}
	$controller->center_db->free_all();

	return $typelist;
}

/**
 * 获得type_object ID和Name对应的数组（商城中的数据）
 * @return array
 */
function get_type_object_dynamic() {
	//把type表读到内存中来
	$typelist=array();
	$controller = &get_instance("controller");
	$dyn_type_connect = $controller->load->database('center_db');
	$sql = "SELECT id, name FROM dynamic_type_object ";
	$dyn_type_connect->query($sql);
	while ($rowtype = $dyn_type_connect->get_array()) {
		//几个特殊的标识需要转换下
		$typelist[$rowtype['id']] = trim($rowtype['name']);
	}
	$dyn_type_connect->free_all();

	return $typelist;
}

/**
 * 获得type_object ID和Name对应的数组（db中的type_object数据）
 * @return array
 */
function get_type_object_db() {
	//把type表读到内存中来
	$typelist=array();
	$controller = &get_instance("controller");
	$controller->load->database('type_db');
	$sql = "SELECT id, name FROM type_object ";
	$controller->type_db->query($sql);
	while ($rowtype = $controller->type_db->get_array()) {
		//几个特殊的标识需要转换下
		$typelist[$rowtype['id']] = trim($rowtype['name']);
	}
	$controller->type_db->free_all();

	return $typelist;
}

/**
 * 获得type_object中详细信息
 * @return array
 */
function get_type_object_detail() {
	//把type表读到内存中来
	$typelist=array();
	$controller = &get_instance("controller");
	$controller->load->database('type_db');
	$sql = "SELECT * FROM type_object ";
	$controller->type_db->query($sql);
	//$this->type_db->query($sql);
	while ($rowtype = $controller->type_db->get_array()) {
		$typelist[$rowtype['id']]['name'] = $rowtype['name'];	//名字
		$typelist[$rowtype['id']]['usedlevel'] = $rowtype['usedlevel'];	//使用最低等级
		$typelist[$rowtype['id']]['actobject'] = $rowtype['actobject'];	//作用对象(0,自己;1,队友;2,光环;3,帮派)
		$typelist[$rowtype['id']]['objecticon'] = $rowtype['objecticon'];	//物品图标
		$typelist[$rowtype['id']]['kind'] = $rowtype['kind'];	//物品类型(10,装备;11,材料;12,时装;13,消耗品;14,任务物品,15称号背包,16宠物背包,17祝福背包)
		$typelist[$rowtype['id']]['subkind'] = $rowtype['subkind'];	//子类型
		$typelist[$rowtype['id']]['color'] = $rowtype['color'];	//物品颜色(0,不分颜色;1,白色;2,蓝色;3,紫色;4,粉色;5,橙色;6,普通;7,高级,8,节日;9,稀有)
		$typelist[$rowtype['id']]['weight'] = $rowtype['weight'];	//物品重量(克)
		$typelist[$rowtype['id']]['stacklimit'] = $rowtype['stacklimit'];	//堆叠上限
		$typelist[$rowtype['id']]['baglimit'] = $rowtype['baglimit'];	//背包上限
		$typelist[$rowtype['id']]['picktype'] = $rowtype['picktype'];	//拾取状态(0,自由交易;1,装备绑定;2,拾取绑定)
		$typelist[$rowtype['id']]['gettype'] = $rowtype['gettype'];	//获得方式(0,商店购买;1,商城购买;2,战斗获得)
		$typelist[$rowtype['id']]['buygold'] = $rowtype['buygold'];	//购买砖石
		$typelist[$rowtype['id']]['sellgold'] = $rowtype['sellgold'];	//出售砖石
		$typelist[$rowtype['id']]['validtime'] = $rowtype['validtime'];	//有效时间(为空则没有倒计时)
		$typelist[$rowtype['id']]['candecompose'] = $rowtype['candecompose'];	//是否可拆解
		$typelist[$rowtype['id']]['describe'] = $rowtype['describe'];	//描述
		$typelist[$rowtype['id']]['useremark'] = $rowtype['useremark'];	//??
	}
	$controller->type_db->free_all();

	return $typelist;
}

/**
 * 获得type_shop ID和Name对应的数组
 * @return array
 */
function get_type_shop() {
	//把type表读到内存中来
	$typelist=array();
	$controller = &get_instance("controller");
	$type_connect = $controller->load->database('type_db');
	$sql = "SELECT id, name FROM type_shop ";
	$type_connect->query($sql);
	while ($rowtype = $type_connect->get_array()) {
		//几个特殊的标识需要转换下
		$typelist[$rowtype['id']] = $rowtype['name'];
	}
	$type_connect->free_all();

	return $typelist;
}

/**
 * 获得type_equip 装备信息
 * @return array
 */
function get_equipment_list() {
	//把type表读到内存中来
	$typelist=array();
	$controller = &get_instance("controller");
	$controller->load->database('type_db');
	$sql = "SELECT * FROM type_equip ";
	$controller->type_db->query($sql);
	//$this->type_db->query($sql);
	while ($rowtype = $controller->type_db->get_array()) {
		//暂时只需要这么向个字段了。。。
		$typelist[$rowtype['id']]['equipgrade'] = $rowtype['equipgrade'];	//装备分类[0,普通;1,高级;2,稀有;3,魔法封印;4,传承;5,异界;6,高级异界;7,神器,8,领主神器;9,史诗;]	
		$typelist[$rowtype['id']]['equipvariety'] = $rowtype['equipvariety'];	//装备品种:0,武器;1,防具;2,首饰;3特殊装备;4,称号
		$typelist[$rowtype['id']]['profession'] = $rowtype['profession'];	//职业:-1,通用;0,战士;1,法师;2,弓箭手;3,圣徒;4,战神;5,狂战士;6,冰霜法师;7,火焰法师;8,死灵术士;9,游侠;10,光明骑士;11,黑暗骑士;
	}
	$controller->type_db->free_all();

	return $typelist;
}

/**
 * 分区数据同步
 * @param mixed $areaids 接收的分区集合 可以使用数组,字符串等,* 表示同步发送到全部分区
 * @param string $title 同步时显示的标题文字
 * @param string $class 类名 可使用__CLASS__
 * @param string $method 方法名 可使用__FUNCTION__
 * @param array $params 参数
 * @param bool $return 是否返回而不输出数据,在json输出时使用
 * @return mixed
 */
function set_async_data($areaids = '*', $title = 'Title', $class = '', $method = '', $params = array(), $return = false) {

	if (!$areaids)
	{
		return array();
	}
	$where = array("1 = 1");
	if ($areaids != '*') {
		$areaids = is_array($areaids) ? $areaids : explode(',', $areaids);
		$where[] = "id IN ('" . implode("','", $areaids) . "')";
	}
	$framework = &get_instance('controller');
	$framework->db->query("SELECT * FROM {pre}areasample WHERE " . implode(" AND ", $where) . " ORDER BY weigh DESC", "list");
	$url = get_method_url($class, $method);
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$t = str_replace("/api/", "", $row['url']);
		$areainfo[] = array('id' => $row['id'], 'name' => $row['name'], 'url' => $t . site_url("api"), 'admin' => $t . site_url());
	}
	$result = array('url' => $url, 'data' => json_encode($params), 'username' => $framework->auth->username);
	$result['sig'] = get_sig($result);
	if ($return) {
		return array($title, $areainfo, $result, num_rand('', 6));
	} else {
		echo "<script type='text/javascript'>window.top.async('{$title}'," . json_encode($areainfo) . "," . json_encode($result) . ", '" . num_rand('', 6) . "');</script>";
	}
}

/**
 * 同步发送数据到单个分区
 * @param string $areaId 分区ID
 * @param string $url 分区接口地址
 * @param array $params 参数
 * @return boolean
 */
function set_async_area($areaId, $url, $params = array()) {
	$framework = &get_instance('controller');
	$area = $framework->db->one("SELECT * FROM {pre}areasample WHERE father_id = id AND id='{$areaId}'");
	if ($area) {
		$result = array('url' => $url, 'data' => json_encode($params));
		$result['sig'] = get_sig($result);
		$areaurl = str_replace("/api/", "", $area['url']) . site_url('api');
		$ret = post($areaurl, $result);
		if ($ret['result']) {
			$json = json_decode($ret['msg'], true);
			if ($json && $json['code'] == 1) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function get_method_url($class, $method) {
	$url = trim($_SERVER['PATH_INFO'], '/');
	if ($method && strripos($url, $method) === false)
	$url .= "/{$method}";
	$class = strtolower(str_replace(array('_Controller', '_Model'), '', $class));
	$s = $class . '/' . $method;
	return substr($url, 0, strripos($url, $s) + strlen($s));
}

function get_used_status() {
	$cpu_usage = $mem_usage = $hd_avail = $hd_used = $hd_usage = $task_running = $hd_total = 0;
	$fp = popen('top -b -n 1 | grep -E "^(Cpu|Mem|Tasks)"', "r"); //获取某一时刻系统cpu和内存使用情况
	$rs = "";
	while (!feof($fp)) {
		$rs .= fread($fp, 1024);
	}
	pclose($fp);
	if ($rs) {
		$sys_info = explode("\n", $rs);
		$task_info = explode(",", $sys_info[0]); //进程 数组
		$cpu_info = explode(",", $sys_info[1]);  //CPU占有量  数组
		$mem_info = explode(",", $sys_info[2]); //内存占有量 数组
		//正在运行的进程数
		$task_running = trim(trim($task_info[1], 'running'));
		//CPU占有量
		$cpu_usage = trim(trim($cpu_info[0], 'Cpu(s): '), '%us');  //百分比
		//内存占有量
		$mem_total = trim(trim($mem_info[0], 'Mem: '), 'k total');
		$mem_used = trim($mem_info[1], 'k used');
		$mem_usage = round(100 * intval($mem_used) / intval($mem_total), 2);  //百分比
		/* 硬盘使用率 begin */
		$fp = popen('df -lh | grep -E "^(/)"', "r");
		$rs = fread($fp, 1024);
		pclose($fp);
		$rs = preg_replace("/\s{2,}/", ' ', $rs);  //把多个空格换成空
		$hd = explode(" ", $rs);
		$hd_total = trim($hd[1], 'G'); //硬盘总空间
		$hd_used = trim($hd[2], 'G'); //硬盘已用空间
		$hd_avail = trim($hd[3], 'G'); //磁盘可用空间大小
		$hd_usage = trim($hd[4], '%'); //硬盘占用百分比
		/* 硬盘使用率 end */
	}
	$result = array('cpu_usage' => $cpu_usage, 'mem_usage' => $mem_usage, 'hd_used' => $hd_used, 'hd_usage' => $hd_usage, 'hd_total' => $hd_total, 'hd_usage' => $hd_usage, 'task_running' => $task_running);
	return $result;
}

/**
 * 写入后台操作日志
 * @param string $modulename 模块名
 * @param string $extramsg 附加信息
 * @param mixed $before 旧数据
 * @param mixed $after 新数据
 */
function insert_log($modulename = array(), $extramsg = array(),$before = null, $after = null) {
	if (is_array($before) && is_array($after)) {
		$original = array_intersect($before, array_diff($before, $after));
		$changed = array_intersect($after, array_diff($after, $before));
	} else {
		$original = $before;
		$changed = $after;
	}
	//$content = $original || $changed ? addslashes(json_encode(array('before' => $original, 'after' => $changed))) : '';
	$content = $original || $changed ? addslashes(json_encode_adv(array('before' => $original, 'after' => $changed))) : '';
	if (!$modulename)
	{
		return;
	}
	$framework = &get_instance('controller');
	$values = array('username' => $framework->auth->username, 'url' => current_url(), 
			'modulename' => addslashes($modulename),'extramsg'=>addslashes($extramsg),
			'content' => $content, 'createtime' => date('Y-m-d H:i:s', time()));
	$framework->db->insert("{pre}admin_log", $values, false, true);
}

function check_env() {
	//预定义查询变量
	$info = array(
        'safe_mode' => array(translate('GENERAL_CHECKENV_INFO_SAFE_MODE'), 0),
        'allow_url_fopen' => array(translate('GENERAL_CHECKENV_INFO_ALLOW_URL_FOPEN'), 'OFF', translate('GENERAL_CHECKENV_SUGGEST_CLOSE')),
        'register_globals' => array(translate('GENERAL_CHECKENV_INFO_REGISTER_GLOBALS'), 'OFF', translate('GENERAL_CHECKENV_SUGGEST_CLOSE')),
        'magic_quotes_gpc' => array(translate('GENERAL_CHECKENV_INFO_MAGIC_QUOTES_GPC'), 'ON', translate('GENERAL_CHECKENV_SUGGEST_OPEN')),
        'short_open_tag' => array(translate('GENERAL_CHECKENV_INFO_SHORT_OPEN_TAG'), 'ON', translate('REQUIRE')),
        'magic_quotes_runtime' => array(translate('GENERAL_CHECKENV_INFO_MAGIC_QUOTES_RUNTIME'), 'OFF', translate('GENERAL_CHECKENV_SUGGEST_CLOSE')),
        'enable_dl' => array(translate('GENERAL_CHECKENV_INFO_ENABLE_DL'), 'OFF', translate('GENERAL_CHECKENV_SUGGEST_OPEN')),
        'display_errors' => array(translate('GENERAL_CHECKENV_INFO_DISPLAY_ERRORS'), 0),
        'post_max_size' => array(translate('GENERAL_CHECKENV_INFO_POST_MAX_SIZE'), 0),
        'upload_max_filesize' => array(translate('GENERAL_CHECKENV_INFO_UPLOAD_MAX_FILESIZE'), 0),
        'memory_limit' => array(translate('GENERAL_CHECKENV_INFO_MEMORY_LIMIT'), 1),
	);

	$fun = array(
        'apc_cache_info' => array(translate('GENERAL_CHECKENV_FUNC_APC_CACHE_INFO'), 0, translate('GENERAL_CHECKENV_SUGGEST_OPEN')),
        'curl_init' => array(translate('GENERAL_CHECKENV_FUNC_CURL_INIT'), 0),
        'mysql_close' => array(translate('GENERAL_CHECKENV_FUNC_MYSQL_CLOSE'), 'ON', translate('REQUIRE')),
        'gd_info' => array(translate('GENERAL_CHECKENV_FUNC_GD_INFO'), 'ON', translate('REQUIRE')),
        'socket_accept' => array(translate('GENERAL_CHECKENV_FUNC_SOCKET_ACCEPT'), 0),
        'xml_set_object' => array(translate('GENERAL_CHECKENV_FUNC_XML_SET_OBJECT'), 'ON', translate('GENERAL_CHECKENV_SUGGEST_OPEN')),
        'gzclose' => array(translate('GENERAL_CHECKENV_FUNC_GZCLOSE'), 0),
        'mcrypt_cbc' => array(translate('GENERAL_CHECKENV_FUNC_MCRYPT_CBC'), 0),
        'preg_match' => array(translate('GENERAL_CHECKENV_FUNC_PREG_MATCH'), 'ON', translate('REQUIRE')),
	);

	$dir = array(
        '/api/application/logs/' => array(translate('GENERAL_CHECKENV_DIR_API_LOGS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        '/api/application/languages/' => array(translate('GENERAL_CHECKENV_DIR_API_LANG'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        '/application/configs/config.php' => array(translate('GENERAL_CHECKENV_DIR_APP_CONFIG'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        '/application/logs/' => array(translate('GENERAL_CHECKENV_DIR_APP_LOGS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        '/application/datas/' => array(translate('GENERAL_CHECKENV_DIR_APP_DATAS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
	site_url('/application/datas/') => array(translate('GENERAL_CHECKENV_DIR_ADMIN_DATAS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
	site_url('/application/logs/') => array(translate('GENERAL_CHECKENV_DIR_ADMIN_LOGS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
	);
	$phpversiON = phpversion();
	$versiON_msg = versiON_compare(PHP_VERSION, '5.3.0', '<') ? translate('GENERAL_CHECKENV_INFO_RECOMMEND_VERSION') : "<span class='blue'>√<span>";
	$run_env = strtoupper(php_sapi_name());
	$os = PHP_OS;
	$is_rewrite = false;
	if (($is_apache = strpos($run_env, 'APACHE')) !== false) {
		$apache_list = apache_get_modules();
		$is_rewrite = array_search('mod_rewrite', $apache_list) ? true : false;
		unset($apache_list);
	}
	foreach ($dir as $key => &$val) {
		$temp = is_writeable(dirname(ROOTPATH) . $key);
		$val['value'] = $temp ? translate('GENERAL_CHECKENV_WREITABLE') : translate('GENERAL_CHECKENV_UNWREITEBLE');
		if ($temp == $val[1]) {
			$val['message'] = '<span class="blue">√</span>';
		} else {
			$val['message'] = '<span class="red">' . $val[2] . '</span>';
		}
	}
	foreach ($info as $key => &$val) {
		$var = get_cfg_var($key) ? get_cfg_var($key) : ini_get($key);
		$val['value'] = ($var == 0) ? 'OFF' : (($var == 1) ? 'ON' : $var);
		if (is_numeric($val[1]) || $val['value'] == $val[1]) {
			$val['message'] = '<span class="blue">√</span>';
		} else {
			$val['message'] = '<span class="red">' . $val[2] . '</span>';
		}
	}
	foreach ($fun as $key => &$val) {
		$val['value'] = function_exists($key) ? 'ON' : 'OFF';
		if (is_numeric($val[1]) || $val['value'] == $val[1]) {
			$val['message'] = '<span class="blue">√</span>';
		} else {
			$val['message'] = '<span class="red">' . $val[2] . '</span>';
		}
	}

	$moban = "<table width='100%' border='0' cellspacing='1' cellpadding='0' class='tablegrid'>
        <tr class='title'><td>" . translate('GENERAL_CHECKENV_INFO_PARAMS') . "</td><td colspan='2'></td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_DOMAINIP') . "：</th><td colspan='2'>{$_SERVER['SERVER_NAME']} [{$_SERVER['REMOTE_ADDR']}]</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_PORT') . "：</th><td colspan='2'>{$_SERVER['SERVER_PORT']}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_SOFTWARE') . "：</th><td colspan='2'>{$_SERVER['SERVER_SOFTWARE']}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_OS') . "：</th><td colspan='2'>{$os}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_ROOT') . "：</th><td colspan='2'>{$_SERVER['DOCUMENT_ROOT']}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_FILENAME') . "：</th><td colspan='2'>{$_SERVER['SCRIPT_FILENAME']}</td></tr>
        <tr class='title'>
            <td class='title'>" . translate('GENERAL_CHECKENV_INFO_VARNAME') . "</td><td class='title'>" . translate('STATUS') . "</td><td class='title'>" . translate('GENERAL_CHECKENV_INFO_COMMEND') . "</td>
        </tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_PHP_VERSION') . "</th><td>{$phpversiON}</td><td>{$versiON_msg}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_PHP_MODE') . "</th><td>{$run_env}</td><td><span class='blue'>√<span></td></tr>";
	$moban .="<tr><th>REWRITE</th><td>";
	if ($is_apache === false) {
		$moban .= translate('UNKNOWN') . "</td><td></td></tr>";
	} else {
		$moban .= ($is_rewrite) ? '<span color="green">' . translate('OPEN') . '</span>' : '<span class="red">' . translate('CLOSE') . '</span>';
		$moban .="</td><td>" . $is_rewrite ? "</td><td><span class='blue'>√<span>" : "<span class='red'>" . translate('REQUIRE') . "<span>" . "</td></tr>";
	}

	$moban .="<tr class='title'><td>" . translate('GENERAL_CHECKENV_DIR') . "</td><td colspan='2'></td></tr>";
	foreach ($dir as $m => $n) {
		$moban.="<tr><th>{$n[0]} [{$m}]</th><td>{$n['value']}</td><td>{$n['message']}</td></tr>";
	}

	$moban .="<tr class='title'><td>" . translate('GENERAL_CHECKENV_INFO') . "</td><td colspan='2'></td></tr>";
	foreach ($info as $m => $n) {
		$moban.="<tr><th>{$n[0]} [{$m}]</th><td>{$n['value']}</td><td>{$n['message']}</td></tr>";
	}

	$moban .="<tr class='title'><td>" . translate('GENERAL_CHECKENV_FUNC') . "</td><td colspan='2'></td></tr>";

	foreach ($fun as $m => $n) {
		$moban.="<tr><th>{$n[0]} [{$m}]</th><td>{$n['value']}</td><td>{$n['message']}</td></tr>";
	}
	$moban .= "</table>";
	return $moban;
}

function readExcel($filePath) {
	require_once(BASEPATH . 'PHPExcel/PHPExcel.php');

	$PHPExcel = new PHPExcel();

	/*     * 默认用excel2007读取excel，若格式不对，则用之前的版本进行读取 */
	$PHPReader = new PHPExcel_Reader_Excel2007();
	if (!$PHPReader->canRead($filePath)) {
		$PHPReader = new PHPExcel_Reader_Excel5();
		if (!$PHPReader->canRead($filePath)) {
			echo 'no Excel';
			return;
		}
	}

	$PHPExcel = $PHPReader->load($filePath);
	/*     * 读取excel文件中的第一个工作表 */
	$currentSheet = $PHPExcel->getSheet(0);
	//print_r($currentSheet);exit();
	/*     * 取得最大的列号 */
	$allColumn = $currentSheet->getHighestColumn();
	/*     * 取得一共有多少行 */
	$allRow = $currentSheet->getHighestRow();
	/*     * 从第二行开始输出，因为excel表中第一行为列名 */
	for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
		/*         * 从第A列开始输出 */
		for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
			$val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65, $currentRow)->getValue(); /*             * ord()将字符转为十进制数 */
			//echo iconv('utf-8','gb2312',$val)."***";
			$excelarray[$currentRow][$currentColumn] = $val;
		}
		//echo "</br></br>";
	}
	//print_r($excelarray);
	return $excelarray;
}

function get_filenamesbydir($dir, $type) {
	$files = array();
	if ($type == 1) {
		get_allfiles($dir, $files);
	} else if ($type == 2) {
		$files = getFile($dir);
	}
	return $files;
}

//获取文件列表
function getFile($dir) {
	$fileArray[] = NULL;
	if (false != ($handle = opendir($dir))) {
		$i = 0;
		while (false !== ($file = readdir($handle))) {
			//去掉"“.”、“..”以及带“.xxx”后缀的文件
			if ($file != "." && $file != ".." && strpos($file, ".")) {
				$fileArray[$i]['filename'] = $file;
				$fileArray[$i]['time'] = filemtime($dir . $file);
				if ($i == 100) {
					break;
				}
				$i++;
			}
		}
		//关闭句柄
		closedir($handle);
	}
	return $fileArray;
}


/**
 * 获得临时数据库的连接
 * @param $platform 平台 0:all ，1:ios正式，2：ios越狱 3:android，4:pc
 * @param $channel 渠道 all:全部 91:91 appstore:appstore, pp:pp
 * @param $dbtype 0:all 1:db 2:dyn 3:type 4:log 5:gm 6:account
 * @param $areanum 区号
 * @return false:没有找到数据库  其它的为success
 */
function getTmpDbConnect($platform, $channel, $areanum, $dbtype = 0) {
	$framework = &get_instance('controller');
	//$sql = "SELECT * FROM server_mapping where platform = '$platform' and qudao='$channel' and areanum  = $areanum and dbtype = $dbtype ";
	$sql = "SELECT * FROM server_mapping where qudao='$channel' and areanum  = $areanum and dbtype = $dbtype ";
	$framework->db->query($sql);

	$dbConn = false;
	if ($row = $framework->db->get_array("default")) {
		$conArr = array(
			'library' => 'database',
            'type' => 'mysql',
			'host'=>$row['dbip'],
			'name'=>$row['dbname'],
			'user'=>$row['username'],
			'password'=>$row['userpwd'],
			'pconnect' => false,
		);
		$dbConn = new Database($conArr);
	}
	//没有找到，并且数据库类型不是全部
	if(false == $row && 0 != $dbtype)
	{
		//就再寻找下
		$sql = "SELECT * FROM server_mapping where platform = '$platform' and qudao='$channel' and areanum  = $areanum and dbtype = 0 ";
		$framework->db->query($sql);
	
		if ($row = $framework->db->get_array("default")) {
			$conArr = array(
				'library' => 'database',
	            'type' => 'mysql',
				'host'=>$row['dbip'],
				'name'=>$row['dbname'],
				'user'=>$row['username'],
				'password'=>$row['userpwd'],
				'pconnect' => false,
			);
			$dbConn = new Database($conArr);
		}else 
		{
			 echo "<script>alert(' can not find platform:$platform channel:$channel areanum:$areanum dbtype:$dbtype');</script>";
			return false;
		}
	}
	
	return $dbConn;
}

/**
 * 通过区号和角色id获取玩家的账号id
 */
function getAccountId($area, $roleid)
{
	$tmp = array();
	$conn = getTmpDbConnect(PLATFORM_ALL, 'all', $area, DBTYPE_GAMESERVER);
	$conn->query("SELECT id, accountid FROM player");
	while ($n = $conn->get_array('default'))
	{
		$tmp[$n['id']] = $n['accountid'];
	}
	foreach ($tmp as $k=>$v)
	{
		if ($k == $roleid)
		{
			return $v;
		}
	}
}

/**
 * 得到获取物品的路径表
 * 
 */
function get_type_addway() {
	
	$data = array();
	$framework = &get_instance('controller');
	//var_dump($this->db);
	$framework->db->query("SELECT * FROM type_addway ORDER BY number DESC", "list");
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$data[$row['number']]['chinaname'] = $row['chinaname'];
		$data[$row['number']]['englishname'] = $row['englishname'];
	}
	return $data;
}

/**
 * 得到获背包类型
 * 
 */
function get_type_package() {
	
	$data = array();
	$framework = &get_instance('controller');
	//var_dump($this->db);
	$framework->db->query("SELECT * FROM type_package ORDER BY number DESC", "list");
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$data[$row['number']]['chinaname'] = $row['chinaname'];
		$data[$row['number']]['englishname'] = $row['englishname'];
	}
	return $data;
}


/**
 * 得到活动类型
 * 
 */
function get_type_activity() {
	
	$data = array();
	$framework = &get_instance('controller');
	//var_dump($this->db);
	$framework->db->query("SELECT * FROM type_activity ORDER BY number DESC", "list");
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$data[$row['number']]['chinaname'] = $row['chinaname'];
		$data[$row['number']]['englishname'] = $row['englishname'];
	}
	return $data;
}


/**
 * 得到邮件来源信息
 * 
 */
function get_type_mailsource() {
	
	$data = array();
	$framework = &get_instance('controller');
	//var_dump($this->db);
	$framework->db->query("SELECT * FROM type_mailsource ORDER BY number DESC", "list");
	$areainfo = array();
	while ($row = $framework->db->get_array("list")) {
		$data[$row['number']]['chinaname'] = $row['chinaname'];
		$data[$row['number']]['englishname'] = $row['englishname'];
	}
	return $data;
}


/**
 * 得到任务名字
 * 
 */
function get_type_task() {
	
	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('type_db');
	$framework->type_db->query("SELECT missionid,name FROM type_mission", "list");
	while ($row = $framework->type_db->get_array("list")) {
		$tmparr = explode(']', $row['name']);
		$tmparr1 = explode('[', $tmparr[1]);
		$data[$row['missionid']] = $tmparr1[0];
	}
	return $data;
}

/**
 * 得到副本名字
 * 
 */
function get_type_copy() {
	
	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('type_db');
	//var_dump($this->db);
	$framework->type_db->query("SELECT id,name FROM type_copy ", "list");
	$areainfo = array();
	while ($row = $framework->type_db->get_array("list")) {
		$data[$row['id']] = $row['name'];
	}
	return $data;
}

/**
 * 得到副本名字（新）
 *
 */
function get_type_fbname() {

	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('type_db');
	//var_dump($this->db);
	$framework->type_db->query("SELECT fbid,fb_name FROM type_dungeon ", "list");
	//$areainfo = array();
	while ($row = $framework->type_db->get_array("list")) {
		$data[$row['fbid']] = $row['fb_name'];
	}
	return $data;
}

/**
 * 得到副本类型
 *
 */
function get_type_fbtype() {

	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('db');
	//var_dump($this->db);
	$framework->db->query("SELECT type,type_name FROM type_fbtype ", "list");
	while ($row = $framework->db->get_array("list")) {
		$data[$row['type']] = $row['type_name'];
	}
	return $data;
}



/**
 * 得到成就名字
 * 
 */
function get_type_achievement() {
	
	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('type_db');
	//var_dump($this->db);
	$framework->type_db->query("SELECT id,name FROM type_achievement ", "list");
	$areainfo = array();
	while ($row = $framework->type_db->get_array("list")) {
		$data[$row['id']] = $row['name'];
	}
	return $data;
}


/**
 * 得到帮派技能名字
 * 
 */
function get_type_gangskill() {
	
	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('type_db');
	//var_dump($this->db);
	$framework->type_db->query("SELECT skill_id,skill_name FROM type_gangskill ", "list");
	$areainfo = array();
	while ($row = $framework->type_db->get_array("list")) {
		$data[$row['skill_id']] = $row['skill_name'];
	}
	return $data;
}


/**
 * 得到技能名字
 * 
 */
function get_type_skill() {
	
	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('type_db');
	//var_dump($this->db);
	$framework->type_db->query("SELECT id,skillname FROM type_skill ", "list");
	$areainfo = array();
	while ($row = $framework->type_db->get_array("list")) {
		$data[$row['id']] = $row['skillname'];
	}
	return $data;
}

/**
 * 得到称号名字
 *
 */
function get_type_title() {

	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('type_db');
	//var_dump($this->db);
	$framework->type_db->query("SELECT id,name FROM type_title ", "list");
	$areainfo = array();
	while ($row = $framework->type_db->get_array("list")) {
		$data[$row['id']] = $row['name'];
	}
	return $data;
}

/**
 * 得到活跃度名字
 *
 */
function get_type_activevalue() {

	$data = array();
	$framework = &get_instance('controller');
	$framework->load->database('type_db');
	//var_dump($this->db);
	$framework->type_db->query("SELECT id,name FROM type_activevalue ", "list");
	$areainfo = array();
	while ($row = $framework->type_db->get_array("list")) {
		$data[$row['id']] = $row['name'];
	}
	return $data;
}

/**
 * 选取一个
 *
 */
function one($id,array $array){
    foreach ($array as $k=>$v){
        if($v['SvrID'] == $id){
            $data=$v;
            return $data;
        }
    }
    return 'wrong ID';
}
/**
 * 获取服务器列表
 */
function get_server_list()
{
    $config = get_config();
    $post_data='{"SessionID":"ewewqw","SessionKey":"wqqew"}';
    $row = vpost($config['host_url'].'gm_server_list',3,$post_data);
    $rows=json_decode($row,true);
    return $rows['SvrList'];
}
